package com.itelite.controller;

import com.github.pagehelper.PageInfo;
import com.itelite.aop.WinControllerPointCut;
import com.itelite.common.info.RedisKey;
import com.itelite.common.info.Result;
import com.itelite.common.util.SecurityUtils;
import com.itelite.domain.dto.Diversion;
import com.itelite.domain.dto.GroupMemberParam;
import com.itelite.domain.dto.UserVo;
import com.itelite.domain.pojo.Group;
import com.itelite.handler.ValidateHandler;
import com.itelite.service.GroupService;
import com.itelite.service.RedisService;
import com.itelite.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/8/7-16:47
 **/
@Api("组模块")
@Slf4j
@RestController
@RequestMapping("/group/api")
public class GroupController {
    @Autowired
    private GroupService groupService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;
    @ApiOperation("获取分组")
    @GetMapping("/groupTree")
    public Result getGroupTree(){
        return Result.success().data("groupTree",groupService.getGroupTree());
    }

    @ApiOperation("获取所有分组")
    @GetMapping("/groups")
    public Result getGroup(){
        return Result.success()
                .data("groups",groupService.getGroups());
    }

    @ApiOperation("新增小组")
    @PostMapping("/addGroup")
    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    @WinControllerPointCut
    public Result addGroup(@RequestBody Map<String,Object>groupParam) throws IOException {
        String result=ValidateHandler.catchErrors(groupParam,"parentId","groupName","groupDetail");
        if (!result.equals(ValidateHandler.VALIDATE_SUCCESS))
            //缺少参数
            return Result.failure(result);
        //新增小组
        if(groupService.addGroup(groupParam)){
            log.info("新增的小组: {}",groupParam.get("groupName"));
            return Result.success();
        }return Result.failure();
    }

    @ApiOperation("修改组信息")
    @PostMapping("/updateGroup")
    @WinControllerPointCut
    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    public Result updateGroup(@Validated Group group, MultipartFile file,BindingResult error){
        if(error.hasErrors()) return Result.failure(ValidateHandler.catchErrors(error));
        if (groupService.updateGroup(group,file)) {
            log.info("修改小组: {}",group.getGroupId());
            return Result.success();
        }return Result.failure();
    }

    @ApiOperation("删除组信息")
    @GetMapping("/deleteGroup/{groupId}")
    @WinControllerPointCut
    public Result deleteGroup(@PathVariable Integer groupId){
        if (groupService.deleteGroup(groupId)) {
            log.info("删除小组: {}",groupId);
            redisService.removeValue(RedisKey.GROUP_TREE);
            return Result.success();
        }return Result.failure();
    }

    @ApiOperation("获取单组信息")
    @GetMapping("/singleGroup/{groupId}")
    public Result getSingleGroup(@PathVariable Integer groupId){
        Group group = groupService.getGroupRoot(groupId);
        if(group!=null)
            group.setChildren(null);
        return Result.success().data("group",group);
    }

    @ApiOperation("成员名单")
    @PostMapping("/groupMember")
    public Result getGroupMember(@RequestBody @Validated GroupMemberParam param ,BindingResult error){
        if(error.hasErrors())return Result.failure(ValidateHandler.catchErrors(error));
        if(param.getKeyword()==null||param.getKeyword().length()==0){
            param.setKeyword(null);
        }
        PageInfo<UserVo> members = groupService.queryGroupMember(param);
        return Result.success().data("members",members);
    }

    @ApiOperation("查询成员")
    @GetMapping("/queryMember/{keyword}")
    public Result queryMember(@PathVariable String keyword){
        List<Map<String,String>> map = userService.queryGroupMemberByKeyword(keyword);
        return Result.success().data("result",map);
    }

    @ApiOperation("获取登录账号的子节点")
    @GetMapping("/childNode")
    public Result getChildNod(){
        Group root = groupService.getUserControlGroup();
        return Result.success().data("group",root);
    }

    @ApiOperation("删除小组成员")
    @GetMapping("/deleteUser/{userId}")
    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    @WinControllerPointCut
    public Result deleteGroupUser(@PathVariable Integer userId){
        if (userService.deleteUser(userId)) {
            log.info("删除小组成员：{}",userId);
            return Result.success();
        }return Result.failure();
    }

    @ApiOperation("修改成员资料")
    @PostMapping("/updateUser")
    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    @WinControllerPointCut
    public Result updateGroupUser(@RequestBody@Validated UserVo user,BindingResult error){
        if (error.hasErrors()) {
            //参数验证未通过
            return Result.failure(ValidateHandler.catchErrors(error));
        }
        if (userService.updateUser(user)) {
            log.info("修改小组成员信息：{}",user);
            return Result.success();
        }
        return Result.failure();
    }

    @ApiOperation("获取下一级小组列表")
    @GetMapping("/lastGroups/{groupId}")
    public Result getLastGroups(@PathVariable Integer groupId){
        List<Group> groups = groupService.getGroupRoot(groupId).getChildren();
        for (Group group : groups) {
            group.setChildren(null);
        }
        return Result.success().data("groups",groups);
    }

    @ApiOperation("小组分流")
    @PostMapping("/diversion")
    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    @WinControllerPointCut
    public Result groupDiversion(@RequestBody Diversion diversion){
        if (groupService.diversionGroup(diversion)) {
            log.info("分流信息：{}",diversion);
            return Result.success("操作成功");
        }return Result.failure("操作失败");
    }

}
